/**
 *
 * 登录框
 */

'use strict';
var React = require('react');
var ReTab = require('../../containers/pc/ReTab.jsx');
var md5 = require('../../library/md5.js');
var ReButton = require('./ReButton.jsx');
var ReMsgButton = require('./ReMsgButton.jsx');
var ReDialog = require('./ReDialog.jsx');
class HkfsLogin extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '',
            pwd: '',
            msgCode: '',
            remember: false,
            checkMsg: {
                name: '请输入正确的手机号码',
                pwd: '请输入正确密码',
                msgCode: '请输入正确验证码',
                imgMsg: '请输入正确的图片验证码'
            },
            checkPattern: {
                name: '(^[\\d]{11}$)',
                pwd: '(^[\\d\\w]{6,12}$)',
                msgCode: '(^[\\d]{6}$)',
                imgMsg: '(^[\\d\\w]{4}$)'
            },
            checkResult: {
                name: true,
                pwd: true,
                msgCode: true,
                imgMsg: true
            }
        };
        this.setOption = this.setOption.bind(this);
        this.checkItems = this.checkItems.bind(this);
        this.getErrorMsgClass = this.getErrorMsgClass.bind(this);
        this.getMsgCode = this.getMsgCode.bind(this);
        this.tabChange = this.tabChange.bind(this);
        this.passWordLogin = this.passWordLogin.bind(this);
        this.msgLogin = this.msgLogin.bind(this);
        this.setCheckOption = this.setCheckOption.bind(this);
        this.rememberUser = this.rememberUser.bind(this);
        this.renderMsgCodeImg=this.renderMsgCodeImg.bind(this);
    }

    //检测数据
    checkItems() {
        var items = Object.keys(this.state.checkPattern);
        var obj = {};
        obj.checkResult = Object.assign({}, this.state.checkResult);
        for (var i = 0; i < items.length; i++) {
            var patternTest = new RegExp(this.state.checkPattern[items[i]], "i");
            if (patternTest.test(this.state[items[i]])) {
                obj.checkResult[items[i]] = true;
            }
            else {
                obj.checkResult[items[i]] = false;
            }
        }
        this.setState(obj);
        //state有可能尚未更新，用state来检测可能会出错，此处提前将检测结果返回供检测函数调用
        return obj;
    }

    getErrorMsgClass(hide) {
        if (hide) {
            return 'hide';
        }
        else {
            return 'normal'
        }
    }

    //获取验证码
    getMsgCode() {
        var result = this.checkItems();
        if (result.checkResult.name) {
            reqwest({
                url: '/api/getMsgCode?mobile=' + this.state.name,
                method: 'get',
                contentType: 'application/json'
            })
                .then(function (data) {
                })
                .fail(function (err, msg) {
                    alert('获取数据出错');
                });
            return true;
        }
        return false;
    }

    //输入值改变
    setOption(objName, event) {
        var obj = {};
        obj[objName] = event.target.value;
        setTimeout(()=> {
            this.setState(obj);
        }, 0);
    }

    setCheckOption(event) {
        this.setState({
            remember: event.target.checked
        })
    }

    rememberUser(userName) {
        if (this.state.remember) {
            localStorage.setItem('HkfsUserRemember', userName);
        }
    }

    tabChange(active) {
        this.setState({
            checkResult: {
                name: true,
                pwd: true,
                msgCode: true
            }
        });
    }



    componentDidMount() {
        if (localStorage.getItem('HkfsUserRemember')) {
            this.setState({
                name: localStorage.getItem('HkfsUserRemember'),
                remember: true
            });
        }
        else {
            this.setState({
                remember: false
            });
        }
    }

    //验证码登录
    msgLogin(event) {
        var self = this;

        var target = event.srcElement ? event.srcElement : event.target;
        if (this.state.checkResult.name && this.state.checkResult.msgCode) {
            target.disabled = 'disabled';
            reqwest({
                url: '/api/phoneLogin',
                method: 'post',
                contentType: 'application/json',
                data: JSON.stringify({
                    name: this.state.name,
                    msgCode: this.state.msgCode,
                    loginType: 1,
                    mobileType: 3
                })
            })
                .then(function (data) {
                    target.disabled = false;
                    var result = data;
                    if (result.resultCode == '200') {
                        sessionStorage.setItem('HkfsUserPhone', result.result.name);
                        self.rememberUser(result.result.name);
                        location.href = '/';
                    }
                    else {
                        ReDialog.showDialog({
                            title: '',
                            ok: '确定',
                            content: result.msg,
                            isMask: true,
                            isCancel: false,
                            result: (result)=> {
                            }
                        });
                    }
                })
                .fail(function (err, msg) {
                    target.disabled = false;
                    ReDialog.showDialog({
                        title: '',
                        ok: '确定',
                        content: '获取数据发生错误，请稍后再试！',
                        isMask: true,
                        isCancel: false,
                        result: (result)=> {
                        }
                    });
                });
        }
    }

//密码登录
    passWordLogin(event) {
        var self = this;
        var target = event.srcElement ? event.srcElement : event.target;
        if (this.state.checkResult.name && this.state.checkResult.pwd&&this.state.checkResult.imgMsg) {
            target.disabled = 'disabled';
            reqwest({
                url: '/api/login',
                method: 'post',
                contentType: 'application/json',
                data: JSON.stringify({
                    name: this.state.name,
                    pwd: md5.hex_md5(this.state.pwd),
                    loginType: 2,
                    mobileType: 3,
                    verifyCode:this.state.imgMsg
                })
            })
                .then(function (data) {
                    target.disabled = false;
                    var result = data;
                    if (result.resultCode == '200') {
                        sessionStorage.setItem('HkfsUserPhone', result.result.name);
                        self.rememberUser(result.result.name);
                        location.href = '/';
                    }
                    else {
                        ReDialog.showDialog({
                            title: '',
                            ok: '确定',
                            content: result.result,
                            isMask: true,
                            isCancel: false,
                            result: (result)=> {
                            }
                        });
                        self.props.msgCodeClick();
                    }
                })
                .fail(function (err, msg) {
                    target.disabled = false;
                    ReDialog.showDialog({
                        title: '',
                        ok: '确定',
                        content: '获取数据发生错误，请稍后再试！',
                        isMask: true,
                        isCancel: false,
                        result: (result)=> {
                        }
                    });
                    self.props.msgCodeClick();
                });
        }
        /* ReDialog.showDialog({
         title: '',
         ok: '确定',
         content: '<div style="margin-top: 100px;"><div style="color:#be091b;font-size: 20px;line-height: 30px">恭喜您，注册成功！</div><div style="color:#be091b;font-size: 20px;line-height: 30px">您已获得0.5%的加息券，请到我的卡券中查看</div><div style="color:#666666;font-size: 14px;margin-top: 44px">您的登录账号是sdf,10秒后自动登录并跳转到首页</div></div>',
         isMask: true,
         isCancel: false,
         dialogWidth:'640px',
         dialogHeight:'400px',
         result: (result)=> {
         alert(result);
         }
         });*/
    }

    //
    renderMsgCodeImg(){
        if(this.props.loading){
            return <div className="Loading">Loading...</div>
        }
        else{
            return <img src={this.props.msgImgUrl} onClick={this.props.msgCodeClick}/>;
        }
    }

    render() {
        return <div className="LoginContainer">
            <ReTab reClass="LoginType" callParent={this.tabChange}>
                <div reTabTitle="密码登录">
                    <div className="TabContent">
                        <div className="LoginItem">
                            <div>
                                <img className="LoginIcon" src="images/pc/login_icon_phone.png"/>
                                <div className="LoginItemName">手机号</div>
                                <input placeholder="请输入登录手机号" className="commonInput longInput"
                                       onChange={this.setOption.bind(this,'name')} value={this.state.name}
                                       onBlur={this.checkItems}/>
                            </div>
                            <div className={this.getErrorMsgClass(this.state.checkResult.name)}>
                                <div className="LoginItemName"></div>
                                <span className="errorMsg">{this.state.checkMsg.name}</span></div>
                        </div>
                        <div className="LoginItem">
                            <div>
                                <img  className="LoginIcon" src="images/pc/login_icon_password.png"/>
                                <div className="LoginItemName">密码</div>
                                <input type="password" placeholder="请输入登录密码" className="commonInput longInput"
                                       onChange={this.setOption.bind(this,'pwd')} onBlur={this.checkItems}/>
                            </div>
                            <div className={this.getErrorMsgClass(this.state.checkResult.pwd)}>
                                <div className="LoginItemName"></div>
                                <span className="errorMsg">{this.state.checkMsg.pwd}</span></div>
                        </div>
                        <div className="LoginItem">
                            <img className="LoginIcon" src="images/pc/login_icon_verification_code.png"/>
                            <div className="LoginItemName">验证码</div>
                            <div className="MsgImgDiv">
                                <input placeholder="请输入图片验证码" className="commonInput shortInput"
                                       onChange={this.setOption.bind(this,'imgMsg')} onBlur={this.checkItems}/>
                                <div className="MsgImgContent">
                                    {this.renderMsgCodeImg()}
                                </div>
                            </div>
                            <div className={this.getErrorMsgClass(this.state.checkResult.imgMsg)}>
                                <div className="LoginItemName"></div>
                                <span className="errorMsg">{this.state.checkMsg.imgMsg}</span></div>
                        </div>
                        <div className="LoginItem LoginTipsDiv">
                            <div className="LoginItemName"></div>
                            <div className="LoginTips">
                                <div className="RememberDiv"><input type="checkbox" type="checkbox"
                                                                    checked={this.state.remember}
                                                                    onChange={this.setCheckOption}
                                                                    ref="remember1"/><span>记住登录名</span></div>
                                <div className="ForgetPassWord"><a>忘记密码？</a></div>
                            </div>
                        </div>
                        <ReButton reClass="loginButton" reButtonClick={this.passWordLogin}> 立即登录</ReButton>
                        <div className="GotoRegister"><span>还没有账户，</span><a href="/register">快速注册</a></div>
                    </div>
                </div>
                <div reTabTitle="验证码登录">
                    <div className="TabContent">
                        <div className="LoginItem">
                            <div>
                                <img className="LoginIcon" src="images/pc/login_icon_phone.png"/>
                                <div className="LoginItemName">手机号</div>
                                <input placeholder="请输入登录手机号" className="commonInput longInput"
                                       onChange={this.setOption.bind(this,'name') } onBlur={this.checkItems}
                                       value={this.state.name}/>
                            </div>
                            <div className={this.getErrorMsgClass(this.state.checkResult.name)}>
                                <div className="LoginItemName"></div>
                                <span className="errorMsg">{this.state.checkMsg.name}</span></div>
                        </div>
                        <div className="LoginItem">
                            <img className="LoginIcon" src="images/pc/login_icon_verification_code.png"/>
                            <div className="LoginItemName">验证码</div>
                            <div className="MsgCodeDiv">
                                <input placeholder="请输入验证码" className="commonInput shortInput"
                                       onChange={this.setOption.bind(this,'msgCode')} onBlur={this.checkItems}/>
                                <ReMsgButton reClass="messageButton" reButtonClick={this.getMsgCode}
                                             count={120}>获取验证码</ReMsgButton>
                            </div>
                            <div className={this.getErrorMsgClass(this.state.checkResult.msgCode)}>
                                <div className="LoginItemName"></div>
                                <span className="errorMsg">{this.state.checkMsg.msgCode}</span></div>
                        </div>
                        <div className="LoginItem LoginTipsDiv">
                            <div className="LoginItemName"></div>
                            <div className="LoginTips">
                                <div className="RememberDiv"><input type="checkbox" checked={this.state.remember}
                                                                    onChange={this.setCheckOption}
                                                                    ref="remember2"/><span>记住登录名</span></div>
                                <div className="ForgetPassWord"><a>忘记密码？</a></div>
                            </div>
                        </div>
                        <ReButton reClass="loginButton" reButtonClick={this.msgLogin}>立即登录</ReButton>
                        <div className="GotoRegister"><span>还没有账户，</span><a href="/register">快速注册</a></div>
                    </div>

                </div>
            </ReTab>
            <ReDialog/>
        </div>
    }
}

module.exports = HkfsLogin;
